package com.lhczf.lucenedb.consumer;

import com.lhczf.lucenedb.production.AbstractDataProduction;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;

/**
 * @author: 刘华春
 * @date: 2019/2/6
 */
@Slf4j
public class WrapThreadFactory implements ThreadFactory {

    private String name;

    public WrapThreadFactory(String name) {
        this.name = name;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = makeThread(r, name);
        if (r instanceof AbstractDataProduction) {
            thread.setUncaughtExceptionHandler(((AbstractDataProduction) r).getWarpExceptionHandler());
        }
        if (r instanceof AbstractDataConsumer) {
            thread.setUncaughtExceptionHandler(((AbstractDataConsumer) r).getWarpExceptionHandler());
        }
        return thread;
    }

    private Thread makeThread(Runnable r, String name) {
        return new Thread(r, name) {
            @Override
            public String toString() {
                String groupName = null == getThreadGroup() ? "" : getThreadGroup().getName();
                return getClass().getSimpleName() + "[" + getName() + "," + getId() + "," + groupName + "]@" + hashCode();
            }
        };
    }
}
